#!/usr/bin/python
# -*- coding: UTF-8 -*-
import os,django
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "shareAPI2020TB.settings")# project_name 项目名称
django.setup()
import logging
import random

server_logger = logging.getLogger("server")
import time
from BaseWeb import models as BaseWeb_models
from tbitem.util import maokoulingClass

from tbitem.util.itemTemplate import ContentFactory, ContentFactory_forDiscuz, ContentFactory_forDjango
from tbitem.util.qiboPOST import bokeePOST, ContentConfig



import json
import jsonpath
import requests


from tbitem import models




#新版京东内容发发帖函数
def step_jd_qb():
    print(123)








def getATitle():
    #从数据库中取出淘宝已经处理过爬取的链接
    run_modelQuery = models.RunModel.objects.first()
    # print(run_modelQuery.modelType)
    if run_modelQuery.modelType == 0:
        querySetList = models.BBSContent.objects.filter(status=2).all()
    elif run_modelQuery.modelType == 1:
        querySetList = models.DIYTitle.objects.filter(status=2).all()
    else:
        querySetList = models.BBSContent.objects.filter(status=2).all()

    return querySetList



def step4():
    server_logger.error(f"step4-----Start")
    try:
        # 调用数据库账号设置：
        bokeeconfig_QuerySetList = models.QiBoAccount.objects.all()
        if not bokeeconfig_QuerySetList:
            server_logger.error(f"step4-----step4企博账号还没有配置呢，请速速配置----")
            return
        else:
            for bokeeAccount in bokeeconfig_QuerySetList:
                server_logger.error(f"step4-----运行账号：{bokeeAccount.username}----")

                querySetList = getATitle()
                # print(querySet.keyword)  #关键词
                # print(querySet.tbid)  # 淘宝id  ->取商品图文，取tbkurl
                # print(querySet.contentWord)  #句子
                for querySet in querySetList:
                    # 尝试取淘宝客推广链接
                    TbIndex_Query = models.TbIndex.objects.filter(tbid=querySet.tbid).first()
                    if not TbIndex_Query.tbkURL:  # 如果没有链接，就开始申请淘宝客链接
                        server_logger.error("没有淘宝客链接，转换链接（店铺，item两个都要）")

                        # id转链接
                        abc = maokoulingClass.maokouling_ONE()
                        abc.pid = bokeeAccount.pid
                        abc.apkey = bokeeAccount.apkey
                        abc.itemid = TbIndex_Query.tbid
                        abc.userid = maokoulingClass.item_to_SELLID(abc)
                        tbkUrl = maokoulingClass.tblink_get_gaoyong(abc)
                        tbShopUrl = maokoulingClass.userid_to_shopTBK_link(abc)

                        # 链接入库
                        TbIndex_Query.tbkURL = tbkUrl
                        TbIndex_Query.tbkShopURL = tbShopUrl
                        TbIndex_Query.save()

                    # 生成发帖模板
                    server_logger.error("step4--生成发帖模板")
                    TBimg_Query = models.TbIMG.objects.filter(tbimg_Index=TbIndex_Query).all()
                    TBComment_Query = models.TbComment.objects.filter(tbComment_Index=TbIndex_Query).all()

                    firstWord_Query = models.TbFirstWord.objects.order_by('?')[:1].first()  # @type:querySet
                    lastWord_Query = models.TbLastWord.objects.order_by('?')[:1].first()   # @type:querySet
                    if not firstWord_Query:
                        firstWord = '买前必看！'
                    else:
                        firstWord = firstWord_Query.firstWord
                    if not lastWord_Query:
                        lastWord = '质量怎么样？'
                    else:
                        lastWord = lastWord_Query.lastWord
                    """
                    TbIndex_Query 实例   tbindex， /商品淘链接/店铺淘链接
                    querySet    实例  BBSContent       /关键词/源标题/
                    TBimg_Query  实例(多)  TbIMG       /商品的图片合集
                    TBComment_Query  实例(多)  TbComment  商品的评论合集
                    """
                    print(TbIndex_Query)
                    print(querySet)
                    print(TBimg_Query)
                    print(TBComment_Query)

                    # 组合成文章 htmlContent
                    server_logger.error("step4--组合成文章 htmlContent")

                    htmlContent = ContentFactory(TbIndex_Query, querySet, TBimg_Query, TBComment_Query)
                    print(666)
                    print(htmlContent)
                    print(123)

                    # 发布内容如果发布成功，就更改tbindex表的状态为3
                    if htmlContent == None:

                        server_logger.error(f"step4-----组合文章出错")
                    else:
                        server_logger.error("step4--运行tbzhu发帖插件")
                        '''扩展插件----本次帖子存储部分（扩展可删除）给本地发帖存的记录'''
                        htmlContentFromDjango, htmlpinglunListFromDjango = ContentFactory_forDjango(TbIndex_Query,
                                                                                                    querySet,
                                                                                                    TBimg_Query,
                                                                                                    TBComment_Query)
                        # 随机获得作者，数据表有绑定获得由pid和喵口令id，用来发帖
                        querySetAuthorList = BaseWeb_models.Author.objects.all()
                        if not querySetAuthorList:
                            # return HttpResponse('没有作者账号了')
                            print('没有作者账号了')
                        querySetAuthor = random.choice(querySetAuthorList)
                        DetailPageQuerySet = BaseWeb_models.DetailPage.objects.create(
                            tbid=querySet.tbid,
                            detail_auther=querySetAuthor,
                            title=querySet.contentLink.title,
                            content=htmlContentFromDjango,
                            tags='',
                            detail_WebFid_id=1)
                        DetailPageQuerySet.save()
                        # 评论生成：

                        for commentItem in htmlpinglunListFromDjango:
                            querySetAuthorRandom = random.choice(querySetAuthorList)  # 随机获得发帖作者
                            CommentQuerySet = BaseWeb_models.Comment.objects.create(
                                comment_auther=querySetAuthorRandom,
                                comment_detailpage=DetailPageQuerySet,
                                comment_content=commentItem,
                                likeNum=1
                            )
                            CommentQuerySet.save()
                        '''扩展插件----本次帖子存储部分（扩展可删除--end）'''
                        server_logger.error("step4--运行tbzhu发帖插件结束")


                        # 发布企博
                        # '''3、发博客'''
                        # # 调用企业博客发帖模块函数块需要的内容----START

                        bokeeconfig = bokeeAccount
                        run_modelQuery = models.RunModel.objects.first()
                        if run_modelQuery.modelType == 0:
                            bokeeconfig.title = f"{firstWord}{querySet.contentLink.title}",
                        elif run_modelQuery.modelType == 1:
                            bokeeconfig.title = f"{querySet.title}",
                        else:
                            bokeeconfig.title = f"{firstWord}{querySet.contentLink.title}",
                        bokeeconfig.content = htmlContent,

                        # print("11111111111111111111111111111111111111111111111")
                        # print(content)
                        # print("11111111111111111111111111111111111111111111111")
                        bokeeconfig.columnName = '值得买',  # 分类名字1
                        bokeeconfig.addType = '值得买',  # 分类2
                        bokeeconfig.tags = '',  # 标签
                        bokeeconfig.brief = ""  # 内容摘要
                        postresult = bokeePOST(bokeeconfig)
                        if postresult == True:
                            # 发帖成功
                            # # 调用企业博客发帖模块函数块需要的内容----END
                            querySet.status = 3
                            querySet.save()
                            time.sleep(50)
                            # cursor.execute(f'update JiSuBBS set 备用 = 3,生成评论内容 = {content}')
                        else:
                            server_logger.error("恭喜帖子发够20篇了,如果没发够,请删除当前的商品id(在data.json里边删除他的数据,他的评论有敏感词),输入任意键退出程序")
                            server_logger.error(f"step4-----帖子数量发够了，请检查----")
                            break
                            # exit(code='帖子数量发够了,退出程序')
                        server_logger.error(f"step4-----运行成功")
                        time.sleep(5)

    except Exception as e:
        server_logger.error(f"step4-----step4出错----{e}")
if __name__ == '__main__':
    step4()  #取出一条 状态2的bbscontent数据，然后发企博,发布成功，设置 BBSContent 表状态为3（已成功发布）



